/**
 * @file request.js
 * @author lili39@didichuxing.com
 * @date 2018-07-06 11:53:35
 */

const fs = require('fs');

const axios = require('axios');
const qs = require('qs');

let cookies = fs.readFileSync('./.cookie', 'utf-8');

const get = (url, params = {}, config = {}) => {
    // console.log(url);
    return axios
        .get(url, {
            headers: {
                Cookie: cookies
            },
            params: {
                ...params
                // _t: new Date().getTime()
            },
            ...config
        })
        .then(async ({ headers, data }) => {
            if (headers['content-type'].match('html')) {
                return data;
            } else if (data.msg.match('登录')) {
                await auth();
                return false;
            }
            console.log('GET:', url, data.code);
            return data;
        });
};

const post = (url, data = {}, config = {}) => {
    return axios
        .post(url, qs.stringify(data), {
            headers: {
                Cookie: cookies
            },
            params: {
                _t: new Date().getTime()
            },
            ...config
        })
        .then(async ({ data }) => {
            console.log('POST:', url, data.msg);
            if (data.msg.match('登录')) {
                await auth();
                return false;
            }
            return data;
        });
};

const auth = () => {
    return require('./login')().then(data => {
        cookies = data;
    });
};

module.exports = {
    get,
    post,
    auth
};
